﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CharitiesLib;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections;
using Charities.ModelViews;
using Charities.Forms;

namespace Charities
{
    public partial class MainWindow : Form
    {
        /** attributes **/
        private int userid = -1;
        private int worthyid { get; set; }
        public bool is_loaded = false;
        private Form fo;
        private bool updated = false;
        private string savefront;
        private string saveback;
        private int personId;
        private GrantComparer comparer = new GrantComparer();

        public bool Updated
        {
            get { return updated; }
            set { updated = value; }
        }

        private Person relativePerson;
        private GrantEditor g = null;

        private string id_images_path = Directory.GetCurrentDirectory() + @"\identifier_photos\";

        public Person RelativePerson
        {
            get { return relativePerson; }
            set { relativePerson = value; }
        }

        private int selectedid = -1;
        private ModelContainer ctx = new ModelContainer();

        /** constructor **/

        public MainWindow(int i, Form f, bool _updated)
        {
            updated = _updated;
            fo = f;
            this.MdiParent = f;
            userid = i;
            InitializeComponent();
        }

        public MainWindow(int i, Form f, bool _updated, int worthyId)
        {
            worthyid = worthyId;
            updated = _updated;
            fo = f;
            this.MdiParent = f;
            userid = i;
            InitializeComponent();
            GetWorthiesNames();
            listBoxWorthies.SelectedValue = worthyid;
            listBoxWorthies_Click(listBoxWorthies.SelectedItem, new EventArgs());
        }

        /****************** methods ******************/

        // clear all text boxes
        private void ClearAll()
        {
            textBoxAmana.Clear();
            textBoxCurrentLodging.Clear();
            textBoxAge.Clear();
            textBoxFamilyNumber.Clear();
            textBoxFatherName.Clear();
            textBoxFirstName.Clear();
            textBoxId.Clear();
            textBoxLaNamest.Clear();
            textBoxMotherName.Clear();
            textBoxNatNumber.Clear();
            textBoxOriginalLodging.Clear();
            textBoxPoP.Clear();
            textBoxQaid.Clear();
            txb_Phone.Clear();
            //-------Enable boxes ---------
            textBoxAmana.Enabled = true;
            textBoxCurrentLodging.Enabled = true;
            textBoxAge.Enabled = true;
            textBoxFamilyNumber.Enabled = true;
            textBoxFatherName.Enabled = true;
            textBoxFirstName.Enabled = true;
            textBoxLaNamest.Enabled = true;
            textBoxMotherName.Enabled = true;
            textBoxNatNumber.Enabled = true;
            textBoxOriginalLodging.Enabled = true;
            textBoxPoP.Enabled = true;
            textBoxQaid.Enabled = true;
            txb_Phone.Enabled = true;
            comboBoxInspector.Enabled = true;
            comboBoxWorthyType.Enabled = true;
            //--------Clear bindings----------
            pictureBoxBack.Image = null;
            pictureBoxFront.Image = null;
            saveback = string.Empty;
            savefront = string.Empty;
        }

        // enable all contorls
        private void EnableAll()
        {
            toolStripMenuItemShowPicture.Enabled = true;
            toolStripMenuItemDelete.Enabled = true;
            toolStripMenuItemEdit.Enabled = true;
            toolStripMenuItemEditPicBack.Enabled = true;
            toolStripMenuItemShowPicBack.Enabled = true;
            toolStripMenuItemDeletePicBack.Enabled = true;
            textBoxAmana.Enabled = true;
            textBoxCurrentLodging.Enabled = true;
            textBoxFamilyNumber.Enabled = true;
            textBoxFatherName.Enabled = true;
            textBoxFirstName.Enabled = true;
            textBoxLaNamest.Enabled = true;
            textBoxMotherName.Enabled = true;
            textBoxNatNumber.Enabled = true;
            textBoxOriginalLodging.Enabled = true;
            textBoxPoP.Enabled = true;
            textBoxQaid.Enabled = true;
            txb_Search.Enabled = true;
            txb_Phone.Enabled = true;
            comboBoxInspector.Enabled = true;
            comboBoxWorthyType.Enabled = true;
            toolStripButtonSave.Enabled = true;
            pictureBoxBack.Enabled = true;
            pictureBoxFront.Enabled = true;
            cbo_Sex.Enabled = true;
            pictureBoxBack.Enabled = true;
            pictureBoxFront.Enabled = true;


            birth_date_label.Text = "تاريخ الميلاد";
            textBoxAge.Visible = false;

        }

        // disable all controls
        private void DisableAll()
        {
            toolStripMenuItemDelete.Enabled = false;
            toolStripMenuItemEdit.Enabled = false;
            toolStripMenuItemEditPicBack.Enabled = false;
            toolStripMenuItemDeletePicBack.Enabled = false;
            cbo_Sex.Enabled = false;
            textBoxAmana.Enabled = false;
            textBoxCurrentLodging.Enabled = false;
            textBoxAge.Enabled = false;
            textBoxFamilyNumber.Enabled = false;
            textBoxFatherName.Enabled = false;
            textBoxFirstName.Enabled = false;
            textBoxLaNamest.Enabled = false;
            textBoxMotherName.Enabled = false;
            textBoxNatNumber.Enabled = false;
            textBoxOriginalLodging.Enabled = false;
            textBoxPoP.Enabled = false;
            textBoxQaid.Enabled = false;
            txb_Phone.Enabled = false;
            comboBoxInspector.Enabled = false;
            comboBoxWorthyType.Enabled = false;
            toolStripButtonSave.Enabled = false;

            birth_date_label.Text = "العمر";
            textBoxAge.Visible = true;

        }

        // check validaty of data: return error messages
        private string CheckValidatyOfData()
        {
            // create variable for error messages
            string error_messages = string.Empty;

            /*** check required fields of person ***/

            if (textBoxFirstName.Text.Trim() == string.Empty)
                error_messages += "الاسم الأول مطلوب\n";
            if (textBoxFatherName.Text.Trim() == string.Empty)
                error_messages += "اسم الأب مطلوب\n";
            if (textBoxLaNamest.Text.Trim() == string.Empty)
                error_messages += "اسم الكنية مطلوب\n";
            if (textBoxNatNumber.Text.Trim() == string.Empty)
                error_messages += "الرقم الوطني مطلوب\n";
            if (textBoxFamilyNumber.Text.Trim() == string.Empty)
                error_messages += "رقم العائلة مطلوب\n";
            if (txb_Phone.Text.Trim() == string.Empty)
                error_messages += "رقم الهاتف مطلوب\n";

            /*** check validaty exists, with notice if this new preson or update exist one ***/
            int id;
            Int32.TryParse(textBoxId.Text.Trim(), out id);

            var per = textBoxId.Text.Trim() != string.Empty
                          ? ctx.People.Where(o => ((o.NationalNumber == textBoxNatNumber.Text) ||
                                                   (o.FirstName == textBoxFirstName.Text &&
                                                    o.LastName == textBoxLaNamest.Text &&
                                                    o.FatherName == textBoxFatherName.Text)) && id != o.Id).ToList()
                          : ctx.People.Where(o => (o.NationalNumber == textBoxNatNumber.Text) ||
                                                  (o.FirstName == textBoxFirstName.Text &&
                                                   o.LastName == textBoxLaNamest.Text &&
                                                   o.FatherName == textBoxFatherName.Text)).ToList();


            if (per.Count() > is_new_Worthy)
                error_messages += "الرقم الوطني مكرر أو الاسم ثلاثي مكرر\n";

            if (textBoxFamilyNumber.Text.Trim() != string.Empty)
            {

                var wor = textBoxId.Text.Trim() != string.Empty
                              ? ctx.Worthies.Where(wo => wo.FamilyNumber == textBoxFamilyNumber.Text.Trim()
                                                         && id != wo.PersonId).ToList()
                              : ctx.Worthies.Where(wo => wo.FamilyNumber == textBoxFamilyNumber.Text.Trim()).ToList();

                if (wor.Count() > is_new_Worthy)
                    error_messages += "رقم العائلة مكرر\n";
            }

            // return result
            return error_messages;
        }

        // bind worthies names to list box
        private void GetWorthiesNames()
        {

            var q = (from p in ctx.People
                     join w in ctx.Worthies
                         on p.Id equals w.PersonId
                     where w.IsActive == true
                     select new ModelViews.WorthiesView
                                {
                                    Id = w.Id,
                                    DisplayName = p.FirstName + " " + p.FatherName + " " + p.LastName,
                                    insertDate = w.InsertDate,
                                    PhoneNumber = w.Phone,
                                    CurrentAddress = w.CurrentAddress,
                                    OreginalAddress = w.OriginalAddress,
                                    WorthyTypeName = w.WorthyType.Name,
                                    NatNumber = p.NationalNumber,
                                    FamilyNumber = w.FamilyNumber

                                });

            if (txb_Search.Text.Length == 0)
            {
                listBoxWorthies.DataSource = q.ToArray();
            }
            else
            {
                ArrayList arr = new ArrayList();
                string[] srch = txb_Search.Text.ToLower().Split(' ');
                foreach (string qry in srch)
                {
                    if (qry.Length != 0)
                    {
                        int id;
                        DateTime dt;
                        if (Int32.TryParse(qry, out id))
                        {
                            arr.AddRange(q.Where(c => c.Id == id || c.FamilyNumber.Contains(qry) ||
                                                      c.NatNumber.Contains(qry) || c.PhoneNumber.Contains(qry)).ToArray());
                        }
                        else if (DateTime.TryParse(qry, out dt))
                        {
                            arr.AddRange(q.Where(c => c.insertDate == dt).ToArray());
                        }
                        else
                        {
                            arr.AddRange(q.Where(c => (c.DisplayName.Contains(qry)
                                                       || c.CurrentAddress.Contains(qry) ||
                                                       c.OreginalAddress.Contains(qry))).ToArray());
                        }
                    }
                }
                listBoxWorthies.DataSource = arr.ToArray(typeof (ModelViews.WorthiesView));
            }

        }

        /****************** events ******************/
        // main window load event: to control of enables/disables some tools (control)
        private void MainWindow_Load(object sender, EventArgs e)
        {
            is_loaded = true;

            // add this form to window list
            ((Forms.FormMDI) fo).addFormToWindowsList(this);

            User user = ctx.Users.Single(u => u.Id == userid);
            foreach (var Item in user.Role.Permissions)
            {
                switch (Item.Name.Trim())
                {
                    case "WORTHIES_ADD":
                        toolStripNewWorthy.Visible = true;
                        break;
                    case "WORTHIES_UPDATE":
                        toolStripButtonEdit.Visible = true;
                        toolStripButtonDelete.Visible = true;
                        break;
                    case "WORTHIES_DELETE":
                        toolStripButtonSave.Visible = true;
                        break;
                    case "WORTHIES_ADD_GRANT":
                        buttonAddGrants.Visible = true;
                        btnDeleteGrant.Visible = true;
                        break;
                    case "MDI_GRANT_REPORT":
                        btn_emptyGrantReport.Visible = true;
                        break;
                    case "WORTHIES_PRINT_EMPTY_REPORT":
                        buttonWorthyReport.Visible = true;
                        break;
                    case "WORTHIES_NEED":
                        buttonGrantsReport.Visible = true;
                        break;
                    case "WORTHIES_GRANTS_REPORT":
                        btn_Relatives_Delete.Visible = true;
                        break;
                    default:
                        break;
                }
            }

        }

        // main windows activate event: to add this window as activate to windows list
        private void MainWindow_Activated(object sender, EventArgs e)
        {
            // activate this form and add it windows list as activate one
            ((Forms.FormMDI) fo).activateWindow(this);

            // bind worthies names to list box
            GetWorthiesNames();
        }

        // new button click event: to add new worthy
        private void toolStripNewWorthy_Click(object sender, EventArgs e)
        {
            // select first tab of worthy data
            tabControlWorthy.SelectTab(0);

            // disable edit & delete button
            toolStripButtonEdit.Enabled = false;
            toolStripButtonDelete.Enabled = false;

            // clear all data fields to add new worthy
            ClearAll();

            // enable all controls
            EnableAll();

            // set lists of worthy type and inspectors
            comboBoxWorthyType.DataSource = (from wt in ctx.WorthyTypes select wt).ToList();
            comboBoxInspector.DataSource = (from i in ctx.Inspectors select i).ToList();

            // reset data/time picker
            birthDateTimePicker.Value = DateTime.Now;
        }

        private int is_new_Worthy = 0;
        // update button click event: to update existing worthy
        private void btn_update_Click(object sender, EventArgs e)
        {
            // select first tab of worthy data
            tabControlWorthy.SelectTab(0);

            // enable all controls
            EnableAll();

            // disable edit & delete button
            toolStripButtonEdit.Enabled = false;
            toolStripButtonDelete.Enabled = false;

            // temprory value for parsing value of id
            int tmpid;

            // try parsing id value
            Int32.TryParse(textBoxId.Text, out tmpid);

            // get person
            Worthy w = ctx.Worthies.Single(c => c.Id == tmpid);
            Person p = ctx.People.Single(s => s.Id == w.PersonId);

            // set birth date
            if (p.DOB != null)
                birthDateTimePicker.Value = p.DOB.Value;
        }

        // worthy report click event: to show worthy report
        private void buttonWorthyReport_Click(object sender, EventArgs e)
        {
            Needs n = new Needs(userid, worthyid, fo);
            n.Show();
        }

        // save changes of worthies data after any change
        private void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                // temprory value for parsing value of id
                int tmpid;

                // try parsing id value
                Int32.TryParse(textBoxId.Text, out tmpid);

                // create worthy & person objects
                Worthy w;
                Person p;

                // Update existing worthy 
                if (tmpid > 0)
                {
                    is_new_Worthy = 1;
                    // get info of worthy / person
                    w = ctx.Worthies.Single(c => c.Id == tmpid);
                    p = ctx.People.Single(s => s.Id == w.PersonId);
                }
                else // Insert new Worthy
                {
                    is_new_Worthy = 0;
                    // create new worthy / person
                    w = new Worthy();
                    p = new Person();
                }

                // check validaty of data
                string error_messages = CheckValidatyOfData();

                // no error
                if (error_messages == string.Empty)
                {
                    /***** Store of person data with checked some of them *****/
                    p.FirstName = textBoxFirstName.Text.Trim();
                    p.FatherName = textBoxFatherName.Text.Trim();
                    p.LastName = textBoxLaNamest.Text.Trim();
                    p.MotherName = textBoxMotherName.Text.Trim();
                    p.NationalNumber = textBoxNatNumber.Text.Trim();
                    p.Qaid = textBoxQaid.Text.Trim().Length > 0 ? textBoxQaid.Text.Trim() : null;
                    p.Amana = textBoxAmana.Text.Trim().Length > 0 ? textBoxAmana.Text.Trim() : null;
                    p.POB = textBoxPoP.Text.Trim().Length > 0 ? textBoxAmana.Text.Trim() : null;
                    p.Sex = cbo_Sex.Text.Trim().Length > 0 ? cbo_Sex.Text : null;
                    p.PhotoFront = pictureBoxFront.Image != null ? GetImageFromFrontPicBox(ofpfront) : null;
                    p.PhotoBack = pictureBoxBack.Image != null ? GetImageFromBackPicBox(ofpback) : null;
                    p.DOB = birthDateTimePicker.Value;
                    p.RelationshipWithWorthy = "المستحق";

                    if (tmpid > 0) // store update time
                    {
                        p.UpdateDate = DateTime.Now;
                        p.UpdateUId = userid; // what do you mean by 1, admin ??
                    }
                    else // store insert time
                    {
                        p.InsertDate = DateTime.Now;
                        p.InsertUId = userid;

                        //// add person to database
                        //ctx.People.Add(p);

                        //// save changes
                        //ctx.SaveChanges();
                    }

                    /***** Store of Worthy data with checked some of them *****/
                    if (tmpid <= 0)
                        w.PersonId = p.Id; // new person, save id of worthy

                    w.FamilyNumber = textBoxFamilyNumber.Text.Trim();
                    w.CurrentAddress = textBoxCurrentLodging.Text.Trim().Length > 0
                                           ? textBoxCurrentLodging.Text.Trim()
                                           : null;
                    w.OriginalAddress = textBoxOriginalLodging.Text.Trim().Length > 0
                                            ? textBoxOriginalLodging.Text.Trim()
                                            : null;
                    w.Phone = txb_Phone.Text.Trim().Length > 0 ? txb_Phone.Text.Trim() : null;
                    w.WorthyTypeId = (int) comboBoxWorthyType.SelectedValue;
                    w.InspectorId = (int) comboBoxInspector.SelectedValue;
                    w.IsActive = true;

                    if (tmpid > 0) // store update time
                    {
                        w.UpdateDate = DateTime.Now;
                        w.UpdateUId = userid;

                    }
                    else // store insert time
                    {
                        w.InsertDate = DateTime.Now;
                        w.InsertUId = userid;

                        // add worthy to database
                        w.People.Add(p);
                        ctx.Worthies.Add(w);


                        //assign id on worthy to person.worthyid
                        //p.WorthyId = w.Id;

                    }


                    // save changes
                    ctx.SaveChanges();
                    w.PersonId = p.Id;
                    ctx.SaveChanges();
                    // disable all controls, except edit & delete button
                    DisableAll();
                    toolStripButtonEdit.Enabled = true;

                    /**** re-bind data ****/
                    if (p.DOB != null)
                    {
                        if (DateTime.Now.Year > p.DOB.Value.Year)
                            textBoxAge.Text = DateTime.Now.AddYears(-p.DOB.Value.Year).Year.ToString();
                        else
                            textBoxAge.Text = "";
                    }

                    if (tmpid <= 0)
                    {
                        // re-bind worthy list box
                        GetWorthiesNames();

                        // select last item
                        listBoxWorthies.SelectedIndex = listBoxWorthies.Items.Count - 1;

                        // assign id to id text box
                        textBoxId.Text = p.Id.ToString();
                    }

                }
                else // there's some errors in data
                    MessageBox.Show(error_messages, ":تأكد من تفحص الأخطاء التالية", MessageBoxButtons.OK);
            }
            catch
            {
                MessageBox.Show("تأكد من كافة الحقول المطلوبة ");
            }
        }

        // list box worthies selected changes: to show details of worthy
        private void listBoxWorthies_Click(object sender, EventArgs e)
        {
            tabControlWorthy.SelectTab(0);
            dgv_persons.DataSource = null;
            ClearAll();
            DisableAll();
            try
            {
                int id = (int) listBoxWorthies.SelectedValue;
                string fullname = listBoxWorthies.SelectedItem.ToString();

                Worthy w = ctx.Worthies.Find(id);
                Person p = ctx.People.Find(w.PersonId);
                worthyid = w.Id;
                personId = w.PersonId;
                textBoxAmana.Text = p.Amana;
                textBoxCurrentLodging.Text = w.CurrentAddress;
                if (p.DOB != null)
                {
                    if (DateTime.Now.Year > p.DOB.Value.Year)
                        textBoxAge.Text = DateTime.Now.AddYears(-p.DOB.Value.Year).Year.ToString();
                    else
                        textBoxAge.Text = "";

                    birthDateTimePicker.Value = p.DOB.Value;
                }
                textBoxFatherName.Text = p.FatherName;
                textBoxFirstName.Text = p.FirstName;
                textBoxId.Text = w.Id.ToString();
                textBoxLaNamest.Text = p.LastName;
                textBoxMotherName.Text = p.MotherName;
                textBoxNatNumber.Text = p.NationalNumber;
                textBoxOriginalLodging.Text = w.OriginalAddress;
                textBoxFamilyNumber.Text = w.FamilyNumber;
                textBoxPoP.Text = p.POB;
                textBoxQaid.Text = p.Qaid;
                txb_Phone.Text = w.Phone;
                if (p.Sex == "أنثى")
                {
                    cbo_Sex.SelectedIndex = 1;
                }
                else
                {
                    cbo_Sex.SelectedIndex = 0;
                }
                try
                {
                   ReadtoFrontPictureBox(p.PhotoFront);
                }
                catch
                {
                }
                try
                {
                    ReadtoPictureBackBox(p.PhotoBack);
                }
                catch
                {
                }
                List<Inspector> ins = ctx.Inspectors.ToList();
                comboBoxInspector.DataSource = ins;
                comboBoxInspector.SelectedValue = w.InspectorId;
                List<WorthyType> types = ctx.WorthyTypes.ToList();
                comboBoxWorthyType.DataSource = types;
                comboBoxWorthyType.SelectedValue = w.WorthyTypeId;
                toolStripButtonEdit.Enabled = true;
                buttonGrantsReport.Enabled = true;
                buttonWorthyReport.Enabled = true;
                toolStripButtonDelete.Enabled = true;
                buttonAddGrants.Enabled = true;
                object[] query = (from g in ctx.Grants.AsEnumerable()
                                  where g.WorthyId == w.Id
                                  select (new GrantView
                                              {
                                                  name =
                                                      " منحة برقم " + g.IssueNumber + "  بتاريخ " +
                                                      g.IssueDate.ToString(),
                                                  issuNum = g.IssueNumber,
                                                  issuDate = g.IssueDate
                                              }))
                    .Distinct(comparer)
                    .ToArray();

                listBoxGrants.DataSource = null;
                listBoxGrants.DataSource = query;
                listBoxGrants.DisplayMember = "name";
                listBoxGrants.ValueMember = "issuNum";
                toolStripButtonEdit.Enabled = true;
                toolStripButtonRelatives.Enabled = true;
                User Iu = ctx.Users.Find(p.InsertUId);
                User Uu = ctx.Users.Find(p.UpdateUId);
                if (Iu != null)
                {
                    toolStripStatusLabelCreatedUser.Text = Iu.username;
                    toolStripStatusLabelCreatedDate.Text = p.InsertDate.Value.ToShortDateString();
                }
                if (Uu != null)
                {
                    toolStripStatusLabelModfiedUser.Text = Uu.username;
                    toolStripStatusLabelModfiedDate.Text = p.UpdateDate.Value.ToShortDateString();
                }
            }
            catch
            {
            }
        }

        // add grants button: to add new grant for selected worthy  
        private void buttonAddGrants_Click(object sender, EventArgs e)
        {
            if (g != null && g.is_loaded)
            {
                g.Activate();
            }
            else
            {
                g = new GrantEditor(userid, worthyid, fo);
                g.Show();
            }
        }






        private string trimstring(string str)
        {
            string temp = str.Replace(':', '_');
            temp = temp.Replace(' ', '_');
            return temp;
        }

        private void pictureBoxBack_DoubleClick(object sender, EventArgs e)
        {

        }

        OpenFileDialog ofpfront = new OpenFileDialog();
        private void btnFront_Click(object sender, EventArgs e)
        {
            try
            {
                ofpfront.Filter = "JPG File|*.jpg|PNG File|*.png";
                if (ofpfront.ShowDialog() == DialogResult.OK)
                {
                    string path = ofpfront.FileName;
                    pictureBoxFront.Load(path);
                }

                toolStripButtonSave.Enabled = true;

            }
            catch
            {
                MessageBox.Show("لقد حصل خطأ أثناء حفظ الصورة", "خطأ");
            }
        }



        private void DeleteBack_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("تأكيد حذف الصورة؟","تأكيد الحذف",MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                Worthy w = ctx.Worthies.Single(c => c.Id == worthyid);
                Person p = ctx.People.Single(c => c.Id == w.PersonId);
                p.PhotoBack = null;
            }
            pictureBoxBack.InitialImage = null;
            pictureBoxBack.Image = null;
            toolStripButtonSave.Enabled = true;
        }


        private void DeleteFront_Click(object sender, EventArgs e)
        {

            DialogResult result = MessageBox.Show("تأكيد حذف الصورة؟", "تأكيد الحذف", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                Worthy w = ctx.Worthies.Single(c => c.Id == worthyid);
                Person p = ctx.People.Single(c => c.Id == w.PersonId);
                p.PhotoFront = null;
                pictureBoxFront.InitialImage = null;
                pictureBoxFront.Image = null;
                //pictureBoxFront.Load();
                toolStripButtonSave.Enabled = true;

            }

        }
        OpenFileDialog ofpback = new OpenFileDialog();
        private void btnBack_Click(object sender, EventArgs e)
        {
            
            try
            {
                ofpback.Filter = "JPG File|*.jpg|PNG File|*.png";
                if (ofpback.ShowDialog() == DialogResult.OK)
                {
                    string path = ofpback.FileName;
                    pictureBoxBack.Load(path);
                }
            }
            catch
            {
                MessageBox.Show("لقد حصل خطأ أثناء حفظ الصورة", "خطأ");
            }
            toolStripButtonSave.Enabled = true;

        }

        private void listBoxGrants_SelectedIndexChanged(object sender, EventArgs e)
        {
            listBoxGrantsDetail.DataSource = null;
            btnDeleteGrant.Enabled = true;

            if (listBoxGrants.SelectedItem != null)
            {
                using (var ctx1 = new ModelContainer())
                {
                    string input = listBoxGrants.SelectedValue.ToString();
                    List<string> gd = new List<string>();
                    List<Grant> gs = ctx1.Grants.Where(g => g.IssueNumber == input && g.WorthyId == worthyid).ToList();
                    foreach (var item in gs)
                    {
                        var qery = ctx1.GrantDetails.Where(d => d.GrantId == item.Id).ToList();
                        foreach (var it in qery)
                        {
                            try
                            {
                                if (item.Schedules.Count() > 0)
                                {
                                    Supply sup = ctx1.Supplies.Single(s => s.Id == it.SupplyId);
                                    string t = "( مجدولة ) " + sup.Name + " عدد: " + it.Amount.ToString();
                                    gd.Add(t);
                                }
                                else
                                {
                                    if (item.IsDelivered == true)
                                    {
                                        Supply sup = ctx1.Supplies.Single(s => s.Id == it.SupplyId);
                                        string t = " ( مسلّمة ) " + sup.Name + " عدد: " + it.Amount.ToString();
                                        gd.Add(t);
                                    }
                                    else
                                    {
                                        Supply sup = ctx1.Supplies.Single(s => s.Id == it.SupplyId);
                                        string t = " ( غير مسلّمة ) " + sup.Name + " عدد: " + it.Amount.ToString();
                                        gd.Add(t);
                                    }
                                }
                            }
                            catch
                            {
                                if (item.Schedules.Count() > 0)
                                {
                                    Cart ca = ctx1.Carts.Single(c => c.Id == item.CartId);
                                    string t = " ( مجدولة ) " + ca.Name + " عدد: " + it.Amount.ToString();
                                    gd.Add(t);
                                }
                                else
                                {
                                    if (item.IsDelivered == true)
                                    {
                                        Cart ca = ctx1.Carts.Single(c => c.Id == item.CartId);
                                        string t = " ( مسلّمة ) " + ca.Name + " عدد: " + it.Amount.ToString();
                                        gd.Add(t);
                                    }
                                    else
                                    {
                                        Cart ca = ctx1.Carts.Single(c => c.Id == item.CartId);
                                        string t = " ( غير مسلّمة ) " + ca.Name + " عدد: " + it.Amount.ToString();
                                        gd.Add(t);
                                    }
                                }
                            }
                        }
                    }
                    listBoxGrantsDetail.DataSource = null;
                    listBoxGrantsDetail.DataSource = gd;
                }
            }
        }
        private void pictureBoxFront_Click(object sender, EventArgs e)
        {
            PictureAddForm p = new PictureAddForm(personId, "front", fo);
            p.Show();
        }

        private void pictureBoxBack_Click(object sender, EventArgs e)
        {
            PictureAddForm p = new PictureAddForm(personId, "back", fo);
            p.Show();
        }

        private void btn_relative_Click(object sender, EventArgs e)
        {
            tabControlWorthy.SelectTab(1);
        }
        
        private void buttonGrantsReport_Click(object sender, EventArgs e)
        {
            GrantsReport g = new GrantsReport(userid, worthyid, fo);
                g.Show();
        }

        private void txb_Search_TextChanged(object sender, EventArgs e)
        {
            GetWorthiesNames();
        }

        private void MainWindow_FormClosed(object sender, FormClosedEventArgs e)
        {
            is_loaded = false;
            // remove this form from windows list
            ((Forms.FormMDI)fo).removeFormFromWindowsList(this);
        }

        private void listBoxGrants_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                listBoxGrantsDetail.DataSource = null;
                string issunumber = listBoxGrants.SelectedValue.ToString();
                List<string> gd = new List<string>();
                //string[] numbers = Regex.Split(input, @"\D+");

                GrantEditor ge = new GrantEditor(userid, worthyid, issunumber, fo);
                ge.Show();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txb_Phone_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsNumber(e.KeyChar) && e.KeyChar !=8)
            {
                e.Handled = true;
            }
        }

        private void toolStripButtonGroupOperations_Click(object sender, EventArgs e)
        {
            Forms.CustomOperationsSearch cos = new Forms.CustomOperationsSearch(userid, fo);
            cos.Show();
        }

        private void toolStripButtonShceduals_Click(object sender, EventArgs e)
        {
            Forms.Shceduals sh = new Forms.Shceduals(userid,fo);
            sh.Show();
        }

        private void btn_emptyGrantReport_Click(object sender, EventArgs e)
        {
            EmptyWorthyReport g = new EmptyWorthyReport(fo);
            g.Show();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int? id = (int)listBoxWorthies.SelectedValue;
            if (id != null||id>0)
            {
                Worthy w = ctx.Worthies.Single(c => c.Id == id);

                DialogResult result = MessageBox.Show("هل تريد بالتاكيد ترقين المستحق ؟ وبالتالي لن يظهر مرة أخرى","تأكيد الترقين",MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    w.IsActive = false;
                    ctx.SaveChanges();
                }
                
            }
        }

        private void pictureBoxFront_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                PictureAddForm p = new PictureAddForm(personId, "front", fo);
                p.Show();
            }
        }

        private void pictureBoxBack_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                PictureAddForm p = new PictureAddForm(personId, "back", fo);
                p.Show();
            }
        }

        private void tabControlWorthy_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (textBoxId.Text != null && textBoxId.Text != "")
                {
                    dgv_persons.Enabled = true;
                    if (tabControlWorthy.SelectedTab == tabPageRelatives)
                    {
                        if (worthyid > 0)
                        {
                            Worthy w = ctx.Worthies.Single(c => c.Id == worthyid);
                            Person p = ctx.People.Single(s => s.Id == w.PersonId);
                            personBindingSource.DataSource = ctx.People.Where(pe => pe.WorthyId == worthyid).ToList();
                            dgv_persons.DataSource = personBindingSource;
                            dgv_persons.Columns["idDataGridViewTextBoxColumn"].Visible = false;
                        }
                    }
                }
                else
                {
                    dgv_persons.Enabled = false;
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            } 
        }
        private void dgv_persons_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            int id = 0;
            if (dgv_persons.Rows[e.RowIndex].Cells[0].Value != null)
            {
                id = (int)dgv_persons.Rows[e.RowIndex].Cells[0].Value;
                if (id == selectedid)
                {
                    updated = true;
                }

            }
            if (updated)
            {
                updated = false;
            }
            else
            {

                if (id > 0)
                {
                    try
                    {
                        Person p = ctx.People.Single(c => c.Id == id);
                        p.UpdateDate = DateTime.Now;
                        p.UpdateUId = userid;
                        if (dgv_persons.Rows[e.RowIndex].Cells[1].Value != null)
                        {
                            p.FirstName = dgv_persons.Rows[e.RowIndex].Cells[1].Value.ToString();
                            try
                            {
                                if (dgv_persons.Rows[e.RowIndex].Cells[6].Value != null)
                                    if (dgv_persons.Rows[e.RowIndex].Cells[6].Value.ToString().Length > 0)
                                    {
                                        int dobi;
                                        DateTime dobD;
                                        if (int.TryParse(dgv_persons.Rows[e.RowIndex].Cells[6].Value.ToString(), out dobi))
                                        {
                                            p.DOB = DateTime.Now.AddYears(-dobi);
                                        }
                                        else if (DateTime.TryParse(dgv_persons.Rows[e.RowIndex].Cells[6].Value.ToString(), out dobD))
                                        {
                                            p.DOB = dobD;
                                        }
                                    }
                            }
                            catch (Exception)
                            {
                                MessageBox.Show(@"يجب أن يدخل التاريخ بصيغة يوم\شهر\سنة");
                            }


                            if (dgv_persons.Rows[e.RowIndex].Cells[2].Value != null)
                                p.LastName = dgv_persons.Rows[e.RowIndex].Cells[2].Value.ToString();
                            if (dgv_persons.Rows[e.RowIndex].Cells[7].Value != null)
                                p.NationalNumber = dgv_persons.Rows[e.RowIndex].Cells[7].Value.ToString();
                            if (dgv_persons.Rows[e.RowIndex].Cells[10].Value != null)
                                p.Sex = dgv_persons.Rows[e.RowIndex].Cells[10].Value.ToString();
                            if (dgv_persons.Rows[e.RowIndex].Cells[11].Value != null)
                                p.JobTitle = dgv_persons.Rows[e.RowIndex].Cells[11].Value.ToString();
                            if (dgv_persons.Rows[e.RowIndex].Cells[12].Value != null)
                                p.HealthStatus = dgv_persons.Rows[e.RowIndex].Cells[12].Value.ToString();
                            if (dgv_persons.Rows[e.RowIndex].Cells[14].Value != null)
                                p.RelationshipWithWorthy = dgv_persons.Rows[e.RowIndex].Cells[14].Value.ToString();
                            if (p.RelationshipWithWorthy.Contains("بن"))
                            {
                                Person worpe = ctx.People.Single(c => c.Id == p.Worthy.PersonId);
                                p.FatherName = worpe.FirstName;
                            }
                            ctx.SaveChanges();
                            ctx.Entry<Person>(p).Reload();
                            dgv_persons.Rows[e.RowIndex].Cells[0].Value = p.Id;
                        }
                    }
                    catch
                    {
                    }
                }
                else
                {
                    try
                    {
                        Person pe = new Person();
                        pe.InsertDate = DateTime.Now;
                        pe.InsertUId = userid;
                        if (dgv_persons.Rows[e.RowIndex].Cells[1].Value != null)
                        {
                            pe.FirstName = dgv_persons.Rows[e.RowIndex].Cells[1].Value.ToString();
                            try
                            {
                                if (dgv_persons.Rows[e.RowIndex].Cells[6].Value != null)
                                    if (dgv_persons.Rows[e.RowIndex].Cells[6].Value != null)
                                        if (dgv_persons.Rows[e.RowIndex].Cells[6].Value.ToString().Length > 0)
                                        {
                                            int dobi;
                                            DateTime dobD;
                                            if (int.TryParse(dgv_persons.Rows[e.RowIndex].Cells[6].Value.ToString(), out dobi))
                                            {
                                                pe.DOB = DateTime.Now.AddYears(-dobi);
                                            }
                                            else if (DateTime.TryParse(dgv_persons.Rows[e.RowIndex].Cells[6].Value.ToString(), out dobD))
                                            {
                                                pe.DOB = dobD;
                                            }
                                        }
                            }
                            catch (Exception)
                            {

                                MessageBox.Show(@"يجب أن يدخل التاريخ بصيغة يوم\شهر\سنة");
                            }
                            if (dgv_persons.Rows[e.RowIndex].Cells[2].Value != null)
                                pe.LastName = dgv_persons.Rows[e.RowIndex].Cells[2].Value.ToString();
                            if (dgv_persons.Rows[e.RowIndex].Cells[7].Value != null)
                                pe.NationalNumber = dgv_persons.Rows[e.RowIndex].Cells[7].Value.ToString();
                            if (dgv_persons.Rows[e.RowIndex].Cells[10].Value != null)
                                pe.Sex = dgv_persons.Rows[e.RowIndex].Cells[10].Value.ToString();
                            if (dgv_persons.Rows[e.RowIndex].Cells[11].Value != null)
                                pe.JobTitle = dgv_persons.Rows[e.RowIndex].Cells[11].Value.ToString();
                            if (dgv_persons.Rows[e.RowIndex].Cells[12].Value != null)
                                pe.HealthStatus = dgv_persons.Rows[e.RowIndex].Cells[12].Value.ToString();
                            if (dgv_persons.Rows[e.RowIndex].Cells[14].Value != null)
                                pe.RelationshipWithWorthy = dgv_persons.Rows[e.RowIndex].Cells[14].Value.ToString();

                            pe.WorthyId = worthyid;
                            ctx.People.Add(pe);
                            ctx.SaveChanges();
                            if (pe.RelationshipWithWorthy != null)
                            {
                                if (pe.RelationshipWithWorthy.Contains("بن"))
                                {
                                    Person worpe = ctx.People.Single(c => c.Id == pe.Worthy.PersonId);
                                    pe.FatherName = worpe.FirstName;
                                }
                            }
                            ctx.SaveChanges();
                            dgv_persons.Rows[e.RowIndex].Cells[0].Value = pe.Id;
                        }
                    }
                    catch (Exception ex )
                    {
                        MessageBox.Show("خطأ: "+ex.Message,"خطأ في إضافة/ تعديل مستحق",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                    }

                }


            }

        }

        private void btn_Relatives_Delete_Click(object sender, EventArgs e)
        {
            Worthy worthy = ctx.Worthies.Single(c=>c.Id==worthyid);
            Person person = ctx.People.Single(c => c.Id == worthy.PersonId);
            DialogResult result = MessageBox.Show(" :هل أنت متأكد من حذف  " + (dgv_persons.SelectedRows.Count).ToString()+" سجل ", "تاكيد الحذف", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                try
                {
                    foreach (DataGridViewRow item in this.dgv_persons.SelectedRows)
                    {
                        if (dgv_persons.Rows[item.Index].Cells[0].Value != null)
                        {
                            int id = (int)dgv_persons.Rows[item.Index].Cells[0].Value;
                            Person p = ctx.People.Single(c => c.Id == id);
                            if (p.Id != person.Id)
                            {
                                ctx.People.Remove(p);
                                dgv_persons.Rows.RemoveAt(item.Index);
                            }
                            ctx.SaveChanges();
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        private void dgv_persons_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgv_persons.Rows[e.RowIndex].Cells[0].Value != null)
            {
                int id = (int)dgv_persons.Rows[e.RowIndex].Cells[0].Value;
                if(id>0)
                {
                    Forms.PersonalForm pe = new Forms.PersonalForm(userid,worthyid,id,fo, this);
                    pe.FormUpdated += new PersonalForm.UpdateFormHandler(btn_insert_Click);
                    pe.Show();
                    selectedid = id;                   
                }
            }
        }

        // insert button event : to add worhies that related to selected worthy
        private void btn_insert_Click(object sender, UpdateFormEventArg e)
        {
            ctx.Entry<Worthy>(ctx.Worthies.Single(c => c.Id == worthyid)).Reload();
            
            foreach (var p in ctx.Worthies.Single(c => c.Id == worthyid).People.ToList())
               ctx.Entry<Person>(p).Reload();

            dgv_persons.DataSource = null;
            personBindingSource.DataSource = null;
            personBindingSource.DataSource = ctx.Worthies.Single(c => c.Id == worthyid).People.ToList();
            dgv_persons.DataSource = personBindingSource;

        }

        private void btnDeleteGrant_Click(object sender, EventArgs e)
        {
            string issuNum = listBoxGrants.SelectedValue.ToString();
            DialogResult res = MessageBox.Show("(هل تريد بالتأكيد حذف المنحة (لن يتم حذف العناصر المسلمة","تأكيد حذف منحة",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
            if (res == DialogResult.Yes)
            {
                string errorstatus = string.Empty;
                Worthy wor = ctx.Worthies.Single(w => w.Id == worthyid);
                foreach (Grant item in wor.Grants.Where(g => g.IssueNumber == issuNum).ToList())
                {
                    if (item.IsDelivered != true)
                    {
                        if (item.Schedules.Count() > 0)
                        {
                            ctx.Database.ExecuteSqlCommand("DELETE FROM dbo.Schedules WHERE GrantId=" + item.Id);
                        }
                        ctx.Database.ExecuteSqlCommand("DELETE FROM dbo.Grants WHERE Id=" + item.Id +"AND IsDelivered <> 'TRUE'");
                        ctx.SaveChanges();
                    }
                    else
                    {
                        errorstatus += listBoxGrants.Text;
                    }
                }
                if (errorstatus.Length > 0)
                {
                    MessageBox.Show(" \n لم يتم حذف العناصر المسلمة من المنحة ذات الرقم  "  + issuNum,"لم يتم حذف منحة",MessageBoxButtons.OK,MessageBoxIcon.Information);
                }
            }
            object[] query = (from g in ctx.Grants.AsEnumerable()
                              where g.WorthyId == worthyid
                              select (new GrantView
                              {
                                  name = " منحة برقم " + g.IssueNumber + "  بتاريخ " + g.IssueDate.ToString(),
                                  issuNum = g.IssueNumber,
                                  issuDate = g.IssueDate
                              })).Distinct(comparer)
                                 .ToArray();

            listBoxGrants.DataSource = null;
            listBoxGrants.DataSource = query;
            listBoxGrants.DisplayMember = "name";
            listBoxGrants.ValueMember = "issuNum";
        }
        PersonalForm supf = null;
        private void listBoxWorthies_DoubleClick(object sender, EventArgs e)
        {
            if (listBoxWorthies.SelectedValue != null)
            {
                int worId = (int)listBoxWorthies.SelectedValue;
                Worthy wor = ctx.Worthies.Single(w => w.Id == worId);
                Person per = ctx.People.Single(p => p.Id == wor.PersonId);
                if (supf != null && supf.is_loaded)
                    supf.Activate();
                else
                {
                    supf = new PersonalForm(userid, worthyid,per.Id, fo, this);
                    supf.Show();
                }
            }
        }
        private byte[] GetImageFromFrontPicBox(OpenFileDialog ofp)
        {
            MemoryStream stream = new MemoryStream();
            //handle Write permissions
            using (Bitmap tempImage = new Bitmap(pictureBoxFront.Image))
            {
                if (ofp.FilterIndex == 0)
                {
                    tempImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                else if (ofp.FilterIndex == 1)
                {
                    tempImage.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                {
                    tempImage.Save(stream, ImageFormat.Gif);
                }
            }

            byte[] pic = stream.ToArray();
            return pic;
        }
        private void ReadtoFrontPictureBox(byte[] pic)
        {
            MemoryStream stream = new MemoryStream(pic);
            pictureBoxFront.Image = Image.FromStream(stream);
        }
        private byte[] GetImageFromBackPicBox(OpenFileDialog ofp)
        {
            MemoryStream stream = new MemoryStream();
            //handle Write permissions
            using (Bitmap tempImage = new Bitmap(pictureBoxBack.Image))
            {
                if (ofp.FilterIndex == 0)
                {
                    tempImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                else if (ofp.FilterIndex == 1)
                {
                    tempImage.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                {
                    tempImage.Save(stream, ImageFormat.Gif);
                }
            }

            byte[] pic = stream.ToArray();
            return pic;
        }
        private void ReadtoPictureBackBox(byte[] pic)
        {
            MemoryStream stream = new MemoryStream(pic);
            pictureBoxBack.Image = Image.FromStream(stream);
        }

        private void dgv_persons_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            try
            {
                int dob;
                if (int.TryParse(dgv_persons.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out dob))
                {
                    dgv_persons.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = DateTime.Now.AddYears(-dob).ToShortDateString();
                }

            }
            catch (Exception)
            {
                
                
            }
        }

        private void btn_Relatives_Add_Click(object sender, EventArgs e)
        {
           
                Forms.PersonalForm pe = new Forms.PersonalForm(userid,worthyid, 0, fo, this);
                pe.FormUpdated += new PersonalForm.UpdateFormHandler(btn_insert_Click);
                pe.Show();
              //  selectedid = id;
           
        }

    }
}